package com.top.mall.main.goods

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import com.top.mall.R
import com.top.mall.app.BaseApplication
import com.top.mall.entity.CartList
import com.top.mall.entity.CateList
import com.top.mall.jetpack.vm.GoodsViewModel
import com.top.mall.main.cart.CartActivity
import com.top.mall.main.goods.adapter.CateTitleAdapter
import kotlinx.android.synthetic.main.activity_goods_category.*
import kotlinx.android.synthetic.main.activity_goods_category.imageViewBack
import kotlinx.android.synthetic.main.include_goods_bottom.*
import java.lang.StringBuilder
import java.text.DecimalFormat
import java.util.ArrayList

class GoodsCategoryActivity : OwnerViewModeActivity<GoodsViewModel>() {


//    private val oneCateList: MutableList<CateList> = mutableListOf()

    private val cateTitleAdapter: CateTitleAdapter = CateTitleAdapter()

    override fun viewModel(): GoodsViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_goods_category

    companion object {
        private const val EXTRA_NAME_CATE = "EXTRA_NAME_CATE"
        fun open(cateList: CateList) {
            val bundle = Bundle().apply {
                putParcelable(EXTRA_NAME_CATE, cateList)
            }
            ActivityUtils.startActivity(bundle, GoodsCategoryActivity::class.java)
        }
    }

    private val mCateList: CateList?
        get() = intent?.extras?.getParcelable(EXTRA_NAME_CATE)

    override fun stateBar(): StatusBar {
        return StatusBar(view = clCategoryBar)
    }

    override fun initView() {

        imageViewBack.setOnClickListener { finish() }
        //设置状态栏颜色
        BarUtils.setStatusBarColor(this, Color.WHITE)

//        oneCateList.addAll(
//            elements = intent.getParcelableArrayListExtra<CateList>(EXTRA_NAME_CATE)
//                ?.toMutableList() ?: mutableListOf()
//        )

        tlCategoryBar.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
                (tab?.tag as? CateList)?.let {
                    viewModel.categoryList(pid = it.id, level = 2)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabSelected(tab: TabLayout.Tab?) {
                (tab?.tag as? CateList)?.let {
                    viewModel.categoryList(pid = it.id, level = 2)
                }
            }
        })

        rvCategoryTitle.adapter = cateTitleAdapter

        //去购物车
        tvGoodsBottomGoCart.setOnClickListener {
            CartActivity.open(activity = this)
        }

        //搜索
        ivCategorySearch.setOnClickListener {
            GoodsSearchActivity.open(activity = this)
        }
    }

    override fun initData() {
        if (BaseApplication.getCartListLiveData().value == null) {
            viewModel.cartIndex()
        }

        viewModel.categoryList()
    }

    override fun initViewMode() {
        viewModel.cateListLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val data = response.data ?: return@Observer
            if (data.level == 1) {
                tlCategoryBar.apply {
                    data.data.forEach {
                        addTab(newTab().setText(it.name).setTag(it))
                    }
                    val index = data.data.indexOfLast {
                        it.id == mCateList?.id ?: 0
                    }

                    getTabAt(if (index == -1) 0 else index)?.select()
                }
            } else if (data.level == 2) {
                cateTitleAdapter.setNewInstance(data.data)
                if (data.data.size == 0) {
                    removeFragment()
                } else {
                    cateTitleAdapter.selectedPosition = 0
                }
            }
//            response.data?.data?.let {
//                cateTitleAdapter.setNewInstance(it)
//                if (it.size == 0) {
//                    removeFragment()
//                } else {
//                    cateTitleAdapter.selectedPosition = 0
//                }
//            }
        })

        cateTitleAdapter.selectedLiveData.observe(this, Observer {
            setFragment(it)
        })

        BaseApplication.getCartListLiveData().observe(this, Observer { cartList ->
            fillDataUndulate(cartList)
        })
    }

    override fun onRestart() {
        super.onRestart()
        categoryFragment?.cartListRestart()
    }

    private fun fillDataUndulate(cartList: MutableList<CartList>) {

        tvGoodsBottomBadgeNum.text = cartList.size.toString()

        var num: Int = 0
        var price: Double = 0.00
        cartList.filter { it.isSelected }.forEach {
            num += it.goods_num
            price += it.goods_num * if (it.active_price == "0")
                it.goods_price.toDouble()
            else it.active_price.toDouble()
        }

        tvGoodsBottomSelectNum.text = StringBuilder()
            .append("已选(").append(num).append(")")
        tvGoodsBottomPrice.text = StringBuilder()
            .append("￥").append(DecimalFormat(("############0.00")).format(price))
    }


    private var categoryFragment: GoodsCategoryFragment? = null

    private fun setFragment(cateList: CateList) {
        supportFragmentManager.beginTransaction().apply {
            replace(R.id.flCategoryGoods, GoodsCategoryFragment.newInstance(cateList).apply {
                categoryFragment = this
            })
        }.commit()
    }

    private fun removeFragment() {
        categoryFragment?.let {
            supportFragmentManager.beginTransaction().remove(it).commit()
        }
    }
}